<?php

namespace app\batch;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use app\models\{Order, Business, Recpeople, OrderGoods, RecpeopleArea, RecpeopleProject};
use think\Facade\Config as Configs;
use app\facade\Mns;
use think\Db;
use app\facade\Redis;
use EasyWeChat\Factory;

class Message extends Command
{
    protected $open = false;
    protected function configure()
    {
        $this->setName('Message')->setDescription('通知');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->doCron();
        die();
    }

    protected function doCron()
    {
        $cmd = "ps aux | grep '/www/server/php/72/bin/php /www/wwwroot/garbage/think Message'|grep -v 'grep'| awk '{print $2}'";
        exec($cmd, $ps, $ret);
        if (count($ps) > 1) {
            die("batch of  is running");
        }
        ini_set('max_execution_time', 0);
        (new Order())->where(['status' => 2, 'message' => 1])->chunk(100, function ($list) {
            foreach ($list as $lists) {
                $frtimes = Redis::get('message' . $lists['id']);
                if ($frtimes) {
                    continue;
                } else {
                    Redis::setex('message' . $lists['id'], 5, 5);
                }
                //通知商家微信消息
                $ordergoods = (new OrderGoods())->where('ordersn', $lists['ordersn'])->find();
                $bussiness = (new Business())->where('id', $lists['businessid'])->find();
                $message = [
                    $bussiness['title'], $lists['ordersn'], $ordergoods['title'], $lists['total'], $lists['created']
                ];
                if (!empty($bussiness['openid'])) {
                    $this->wechattest($bussiness['openid'], '您好，您的店铺有新的订单', $message, '【商家信息通知】', 1);
                }
                //通知服务人员
                $recpeople = (new Recpeople())->where(['status' => 1, 'business' => $lists['businessid']])->select();
                $opens = [];
                foreach ($recpeople as $people) {
                    $area = (new RecpeopleArea())->where(['street' => $lists['street'], 'type' => 1, 'peoples' => $people['id']])->find();
                    if (!empty($area) && !empty($people['openid'])) {
                        if ($lists['type'] == 1) {
                            $project = (new RecpeopleProject())->where('peoples', $people['id'])->value('goodsid');
                            $project = json_decode($project, true) ?? [];
                            if (count($project) > 0 && in_array($ordergoods['goodsid'], $project)) {
                                $opens[] = $people['openid'];
                            }
                        } elseif ($lists['type'] == 2 || $lists['type'] == 3) {
                            $opens[] = $people['openid'];
                        }
                    }
                }
                foreach ($opens as $open) {
                    $this->wechattest($open, '您好，您负责区域有新的订单', $message, '【师傅信息通知】', 2);
                }
                (new Order())->where(['id' => $lists['id']])->update(['message' => 2]);
            }
        });

        /*退款通知 */
        $orderid = Redis::lPop('tuikuan');
        if ($orderid) {
            $lists = (new Order())->where(['id' => $orderid])->find();
            if ($lists) {
                $bussiness = (new Business())->where('id', $lists['businessid'])->find();
                $message = [
                    $lists['ordersn'], '取消订单', $lists['total'], $lists['created'], '用户名：' . $lists['name'] . ' 联系电话：' . $lists['mobile']
                ];
                if (!empty($bussiness['openid'])) {
                    $this->wechattest2($bussiness['openid'], '您好，您的店铺有支付订单取消待审核', $message, '取消原因:' . $lists['text'] ?? '');
                }
            }
        }
        //Redis::lPush('tuikuan', $orderid);
    }


    //订单通知
    public function wechattest($touser = '', $first = '', $data, $remark = '', $type = 0)
    {
        $config = config('wechat2.');
        $app = Factory::officialAccount($config);
        if ($type == 1) {
            $url = 'business.tcwang888.com';
        } else {
            //跳转师傅端
            $miniprogram = [
                'appid' => 'wxbea4b447b125b632',
                'pagepath' => '/',
            ];
        }
        $send_data = [
            'template_id' => 'FWkYSzgOUMUfxyKfmvY4MEtyTsOmTRDWtgBJBBu93W4', // 所需下发的订阅模板id
            'touser' => $touser,     // 接收者（用户）的 openid
            'data' => [
                'first' => [
                    'value' => $first
                ],
                'keyword1' => [
                    'value' => $data[0] ?? ''
                ],
                'keyword2' => [
                    'value' =>  $data[1] ?? ''
                ],
                'keyword3' => [
                    'value' => $data[2] ?? ''
                ],
                'keyword4' => [
                    'value' =>  $data[3] ?? ''
                ],
                'keyword5' => [
                    'value' =>  $data[4] ?? ''
                ],
                'remark' => [
                    'value' => $remark
                ],
            ],
        ];
        if (!empty($miniprogram)) {
            $send_data['miniprogram'] = $miniprogram;
        } else {
            $send_data['url'] = $url ?? '';
        }
        $rm = $app->template_message->send($send_data);
        dump($rm);
    }

    //取消订单通知
    public function wechattest2($touser = '', $first = '', $data, $remark = '')
    {
        $config = config('wechat2.');
        $app = Factory::officialAccount($config);
        $send_data = [
            'template_id' => '-7dl7Bvk9waDChyX866KVTTAre8DZ0fL1orQwpwBNsw', // 所需下发的订阅模板id
            'touser' => $touser,     // 接收者（用户）的 openid
            'miniprogram' => [
                'appid' => config('wechat.')['app_id'],
                'pagepath' => '/',
            ],
            'data' => [
                'first' => [
                    'value' => $first
                ],
                'keyword1' => [
                    'value' => $data[0] ?? ''
                ],
                'keyword2' => [
                    'value' =>  $data[1] ?? ''
                ],
                'keyword3' => [
                    'value' => $data[2] ?? ''
                ],
                'keyword4' => [
                    'value' =>  $data[3] ?? ''
                ],
                'keyword5' => [
                    'value' =>  $data[4] ?? ''
                ],
                'remark' => [
                    'value' => $remark
                ],
            ],
        ];
        $rm = $app->template_message->send($send_data);
        dump($rm);
    }
}
